import AntModal from '@/components/pt/dialog/AntModal'
import BizProduct from '@/views/biz/bizorder/modules/BizProduct'
import { getBizInventoryOpening, addBizInventoryOpening, updateBizInventoryOpening } from '@/api/biz/bizInventoryOpening'
import SelectUser from "@/components/pt/selectUser/SelectUser";
import SelectDept from "@/components/pt/selectDept/SelectDept";
import AdvanceTable from "@/components/pt/table/AdvanceTable";
import {listBizWarehouseSpaceByWarehouseId} from "@/api/biz/bizWarehouseSpace";
import ImportExcel from './ImportExcel';
import {randomUUID} from '@/utils/util';
import tableDragResizeMixin from '@/mixins/tableDragResizeMixin'
export default {
  name: 'CreateForm',
  mixins:[tableDragResizeMixin],
  props: {
    statusOptions: {
      type: Array,
      required: true
    },
    warehouseIdOptions: {
      type: Array,
      required: true
    },
  },
  components: {
    AntModal,
    SelectUser,
    SelectDept,
    BizProduct,
    AdvanceTable,
    ImportExcel
  },
  data () {
    return {
      disabledCreated:false,
      showProductModal:false,
      multiple:false,
      open: false,
      closeDialog: true,
      spinning: false,
      delayTime: 100,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      loading: false,
      disabled: false,
      total: 0,
      id: undefined,
      formTitle: '添加库存期初',
      spaceList:[],
      // 表单参数
      form: {},
      uploadLoading:false,
      rules: {
        warehouseId: [{ required: true, message: '仓库不能为空', trigger: 'blur' }],
      },
      columns: [
        { title: '序号', dataIndex: 'rowIndex', width:60, align:"center",
          scopedSlots: {
            customRender: 'rowIndexSlot'
          },
        },
        {
          title: '存货编码',
          dataIndex: 'productCode',
          align: 'center',
          width: '15%'
        },
        {
          title: '品牌',
          dataIndex: 'brand',
          align: 'center',
          width: '5%'
        },
        {
          title: '规格',
          dataIndex: 'spec',
          align: 'center',
          width: '10%'
        },
        {
          title: '颜色',
          dataIndex: 'color',
          align: 'center',
          width: '8%'
        },
        {
          title: '型号',
          dataIndex: 'model',
          align: 'center',
        },
        {
          title: '仓位',
          dataIndex: 'spaceId',
          align: 'center',
          width: '8%',
          scopedSlots: {
            customRender: 'spaceIdSlot'
          },
        },
        {
          title: '数量',
          dataIndex: 'productNumber',
          align: 'center',
          scopedSlots: {
            customRender: 'productNumberSlot'
          },
          width: '7%'
        },
        {
          title: '单位',
          dataIndex: 'unit',
          align: 'center',
          scopedSlots: {
            customRender: 'unitSlot'
          },
          width: '7%'
        },
        {
          title: '单价',
          dataIndex: 'unitPrice',
          align: 'center',
          scopedSlots: {
            customRender: 'unitPriceSlot'
          },
          width: '7%'
        },
        {
          title: '金额',
          dataIndex: 'totalAmount',
          align: 'center',
          scopedSlots: {
            customRender: 'totalAmountSlot'
          },
          width: '7%'
        },
        {
          title: '备注',
          dataIndex: 'remark',
          align: 'center',
          scopedSlots: {
            customRender: 'remarkSlot'
          },
          width: '10%'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          align: 'center',
          width: '25%',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      list: [],
      selectedRowKeys:[],
      ids:[],
    }
  },
  filters: {},
  created () {
    this.initColumnsSetting('initStockDetail')
  },
  computed: {},
  watch: {},
  mounted () {},
  methods: {
    /**
     * @获取上传组件状态
     */
    upload(){
      this.uploadLoading = true
    },
    /**
     * @上传成功回调
     * @param {obj} res 
     */
    importSUccess(res){
      this.uploadLoading = false;
      if(res.code == 200){
        let detailsList = res.data || []
        this.form.detailsList = detailsList.map(v=>{
          v.unitList = [
            {key:1,name:v.unit},
            {key:2,name:v.assistUnitA},
            {key:3,name:v.assistUnitB},
          ]
          v.unit = v.defaultOutboundUnit
          v.productNumber = v.number || 0
          v.id = randomUUID()
          return v
        })
        this.$message.success('数据载入成功！')
      }else{
        this.$message.error(res.msg)
      }
    },
    importTemplate(){
      this.$nextTick(()=>{
        this.$refs.importExcel.importExcelHandleOpen()
      })
    },
    onClose () {
      this.open = false
      this.reset()
      this.$emit('close')
    },
    // 取消按钮
    cancel () {
      this.open = false
      this.reset()
      this.$emit('close')
    },
    // 表单重置
    reset () {
      this.form = {
        id: undefined,
        orderNo: undefined,

        warehouseId: undefined,

        quantity: undefined,

        tenantId: undefined,

        status: '0',

        detailsList : [],

      }
    },
    
    /** 新增按钮操作 */
    handleAdd () {
      this.reset()
      this.open = true
      this.formTitle = '添加库存期初'
      this.selectWarehouse();
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset()
      this.open = true
      this.spinning = !this.spinning
      this.loading = true
      const bizInventoryOpeningId = row.id
      getBizInventoryOpening(bizInventoryOpeningId).then(response => {
        this.form = response.data
        this.form.detailsList = this.form.detailsList.map(v=>(v.unit = +v.unit,v.totalAmount = +v.totalAmount,v))
        this.formTitle = '修改库存期初'
        this.spinning = !this.spinning
        this.loading = false
        this.selectWarehouse();
      })
    },
    /** 提交按钮 */
    submitForm: function (closeDialog) {
      this.closeDialog = closeDialog
      this.disabled = true
      this.loading = true
      this.$refs.form.validate(valid => {
        if (valid) {
          const saveForm = JSON.parse(JSON.stringify(this.form))
          if (this.form.id !== undefined) {
            updateBizInventoryOpening(saveForm).then(response => {
              this.$message.success('更新成功', 3)
              this.open = false
              this.$emit('ok')
              this.$emit('close')
              this.disabled = false
              this.loading = false
            })
          } else {
            addBizInventoryOpening(saveForm).then(response => {
              this.$message.success('新增成功', 3)
              this.open = false
              this.$emit('ok')
              this.$emit('close')
              this.disabled = false
              this.loading = false
            })
          }
        } else {
          this.disabled = false
          return false
        }
      })
    },
    back () {
      const index = '/biz/bizinventoryopening/index'
      this.$router.push(index)
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.ids = this.selectedRows.map(item => item.id)
      this.single = selectedRowKeys.length == 1
      this.multiple = selectedRowKeys.length
    },
    handleSubUpdate() {

    },
    handleSubDelete(row) {
      var that = this
      const productIds = row.id || this.ids
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk () {
          let selectedList = JSON.parse(JSON.stringify(that.list));
          selectedList.forEach((item,index)=>{
            if(row.id) {
              that.list= that.list.filter(item => item.id!=row.id)
              return;
            } else {
              that.selectedRows.forEach(item2=>{
                that.list= that.list.filter(item => item.id!=item2.id)
                return;
              })
            }
          })
          that.$message.success(
            '删除成功',
            3
          )
          that.onSelectChange([], [])
          return;
        },
        onCancel () {}
      })
    },
    handleAddProduct() {
      this.showProductModal = true
      this.$nextTick(() => {
        this.$refs.bizProduct.handleAddProduct(this.list);
      })
    },
    selectWarehouse() {
      listBizWarehouseSpaceByWarehouseId(this.form.warehouseId).then(res=>{
        this.spaceList=res.data;
      });
    },
    selectProduct(selectedRows) {
      selectedRows.forEach(item=>{
        item.unitList = [{key:1,name:item.unit},{key:2,name:item.assistUnitA},{key:3,name:item.assistUnitB}]
        item.quantity = 0;
        item.tempSalePrice = item.salePrice;
        if (item.defaultWarehousingUnit == 2) {
          item.unit = 2
          item.unitPrice = item.salePriceA
        } else if (item.defaultWarehousingUnit == 3) {
          item.unit = 3
          item.unitPrice = item.salePriceB
        } else {
          item.unit = 1;
          item.unitPrice=item.salePrice;
        }
        item.totalAmount = 0.00;
        this.$forceUpdate();
      })
      this.form.detailsList = [...this.form.detailsList,...selectedRows];
    },
    handleChange(info) {
      if (info.file.status == 'done') {
        this.fileList=info.fileList;
      }
    },
    handleRemove(info) {
      this.fileList=this.fileList.filter(function(item) {
        return item.uid != info.uid
      })
    },
    /**
     * 
     * @param {obj} record 
     * 删除期初明细里面的某一条数据
     */
    handleDelete(record,index){
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk:()=>{
          this.form.detailsList.splice(index,1)
        }
      })
    },
    changeUnit(record) {
      // if (record.unit == 1) {
      //   record.unitPrice = record.tempSalePrice;
      // } else if (record.unit == 2) {
      //   record.unitPrice = record.salePriceA;
      // } else if (record.unit == 3) {
      //   record.unitPrice = record.salePriceB;
      // }
      console.log('record :>> ', record);
      let total = +record.unitPrice * +record.productNumber;
      record.totalAmount = total || 0
      this.$forceUpdate();
    },
    selectUnit(record) {
      console.log('record :>> ', record);
      if (record.unit == 1) {
        record.unitPrice = record.purchasesPrice;
      } else if (record.unit == 2) {
        record.unitPrice = record.purchasesPriceA;
      } else if (record.unit == 3) {
        record.unitPrice = record.purchasesPriceB;
      }
      record.totalAmount = this.$toDecimal(record.unitPrice * record.productNumber);
      this.$forceUpdate();
    }
  }
}
